#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<random>
#include<algorithm>
#define N 3
using namespace std;
const int sx[4]={1,-1,0,0};
const int sy[4]={0,0,1,-1};
int n=3,m=3,delta[N+1][N+1];
bool used[N+1];
void dfs(int x,int y)
{
	if (x==n)
	{
		int res=0;
		bool opt=1;
		for (int i=0;i<=n-1;++i)
			for (int j=0;j<=m-1;++j)
			{
				used[0]=used[1]=used[2]=0;
				for (int op=0;op<=3;++op) used[delta[(i+sx[op]+n)%n][(j+sy[op]+m)%m]]=1;
				for (int op=0;op<=3;++op)
					for (int op2=op+1;op2<=3;++op2)
						if (delta[(i+sx[op]+n)%n][(j+sy[op]+m)%m]==delta[(i+sx[op2]+n)%n][(j+sy[op2]+m)%m])
							res+=sx[op]+sy[op]+sx[op2]+sy[op2];
				if (!used[0]||!used[1]||!used[2]) opt=0;
			}
		if (opt)
		{
			cerr<<"CALC"<<res<<endl;
			for (int i=0;i<=n-1;++i)
			{
				for (int j=0;j<=n-1;++j) cerr<<delta[i][j]<<' ';
				cerr<<endl;
			}
		}
		return;
	}
	for (int i=0;i<=2;++i)
	{
		delta[x][y]=i;
		if (y+1<=m-1) dfs(x,y+1);
		else dfs(x+1,0);
	}
	return;
}
int main()
{
	dfs(0,0);
	return 0;
}
